package com.xuecheng.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * 自定义拦截器
 */
public class AuthInfoInterceptor implements HandlerInterceptor {
    /**
     * 进入controller方法之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头中的payload
        if (StringUtils.isEmpty(request.getHeader("payload"))) {
            return true;
        }
        String decode = URLDecoder.decode(request.getHeader("payload"), "utf-8");
        //String decode = request.getHeader("payload");

        //3、转化成AuthInfo对象
        AuthInfo authInfo = JSON.parseObject(decode, AuthInfo.class);
        //4、存入ThreadLocal
        AuthInfoHolder.setAuthInfo(authInfo);
        //true: 向后执行controller方法
        return true;
    }

    /**
     * 在响应结束之前执行
      * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
